package com.lingshu.app.ui.main;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Point;
import android.view.View;
import android.widget.TextView;

import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.core.view.GravityCompat;
import androidx.customview.widget.ViewDragHelper;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.ViewModelProvider;

import com.lingshu.app.R;
import com.lingshu.app.base.BaseActivity;
import com.lingshu.app.config.App;
import com.lingshu.app.config.Constants;
import com.lingshu.app.databinding.ActivityMainBinding;
import com.lingshu.app.ui.login.LoginActivity;
import com.lingshu.app.ui.register.RegisterFragment;
import com.lingshu.app.utils.FileUtils;
import com.lingshu.core.eventbus.BaseSubscriber;
import com.lingshu.core.eventbus.EventBusManager;
import com.lingshu.core.eventbus.EventData;
import com.lingshu.core.eventbus.EventKey;

import java.lang.reflect.Field;

import dagger.hilt.android.AndroidEntryPoint;
import io.reactivex.Single;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * @author 于定金
 * @version 1.0
 * @Date 2024/1/3 11:14
 * @Description
 */
@AndroidEntryPoint
public class MainActivity extends BaseActivity<ActivityMainBinding, MainViewModel> {
    private FragmentManager fragmentManager;
    private RegisterFragment fragment;
    BaseSubscriber<String> subscriber;
    View headerView;
    TextView doctorView;

    /**
     * 获取当前页面的布局资源ID
     *
     * @return 布局资源ID
     */
    @Override
    protected int getLayoutResId() {
        return R.layout.activity_main;
    }

    /**
     * 初始化ViewModel
     */
    @Override
    protected void initViewModel() {
        viewModel = new ViewModelProvider(this).get(MainViewModel.class);
    }

    /**
     * 绑定ViewModel
     */
    @Override
    protected void bindViewModel() {
        dataBinding.setViewModel(viewModel);
    }

    /**
     * 初始化
     */
    @Override
    protected void init() {
        super.init();
        fragment = new RegisterFragment();
        fragmentManager = getSupportFragmentManager();
        loadFragment(fragment);

        headerView = dataBinding.navView.getHeaderView(0);
        doctorView = headerView.findViewById(R.id.doctor_name);
        doctorView.setText(App.getMvUtils().getString(Constants.USER_NAME));

        dataBinding.toolBar.setNavigationOnClickListener(v -> {
            if (dataBinding.drawerView.isDrawerOpen(GravityCompat.START)) {
                dataBinding.drawerView.closeDrawer(GravityCompat.START);
            } else {
                dataBinding.drawerView.openDrawer(GravityCompat.START);
            }
        });

        //让DrawerLayout和Toolbar进行联动  顺序很重要!
        setSupportActionBar(dataBinding.toolBar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        //通过ActionBarDrawerToggle将Toolbar与DrawerLayout关联起来
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(context, dataBinding.drawerView, dataBinding.toolBar, R.string.open, R.string.close);
        //设置监听
        dataBinding.drawerView.addDrawerListener(toggle);
        //同步
        toggle.syncState();

        setDrawerLeftEdgeSize(context, dataBinding.drawerView, 1);

        //设置navigationView中菜单的点击事件
        dataBinding.navView.setNavigationItemSelectedListener(item -> {
            int itemId = item.getItemId();
            if (itemId == R.id.menu_logout) {
                logout();
            } else if (itemId == R.id.menu_delete) {
                deleteDirectory();
            }
            dataBinding.drawerView.closeDrawer(GravityCompat.START);
            return true;
        });

        dataBinding.btnRefresh.setOnClickListener(v -> EventBusManager.post(new EventData<>(EventKey.Refresh, "refresh")));

        if (subscriber == null)
            subscriber = new BaseSubscriber<String>(EventKey.Refresh) {
                @Override
                protected void notifyDataChanged(String value) {
                    if (value.equals("refresh")) {
                        context.recreate();
                        viewModel.infoMsg.postValue(null);
                    }
                }
            };
        if (subscriber != null)
            EventBusManager.register(subscriber);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (subscriber != null)
            EventBusManager.unregister(subscriber);
    }

    /**
     * 切换不同的Fragment
     *
     * @param fragment
     */
    private void loadFragment(Fragment fragment) {
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        // 使用 FragmentTag 来避免重复添加
        if (fragmentManager.findFragmentById(R.id.main_content) == null) {
            transaction.add(R.id.main_content, fragment);
            transaction.commit();
        } else {
            transaction.replace(R.id.main_content, fragment);
            transaction.commit();
        }
    }

    /**
     * 清空数据
     */
    private void deleteDirectory() {
        Single.create(emitter -> {
            try {
                FileUtils.deleteDirectory(context.getExternalCacheDir());
                emitter.onSuccess(true);
            } catch (Exception ex) {
                emitter.onError(ex);
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(success -> {
            EventBusManager.post(new EventData<>(EventKey.Refresh, "refresh"));
            dataBinding.drawerView.close();
        }, throwable -> {
            viewModel.infoMsg.postValue(throwable.getMessage());
        });
    }

    /**
     * 退出
     */
    private void logout() {
        startActivity(new Intent(context, LoginActivity.class));
        context.finish();
    }

    /**
     * 解决DrawerLayout不能全屏滑动的问题
     * 第一个参数传入当前的Activity，第二个参数传入DrawerLayout的对象，最后一个参数 传 1，即可实现全屏滑动
     *
     * @param activity
     * @param drawerLayout
     * @param displayWidthPercentage
     */
    private void setDrawerLeftEdgeSize(Activity activity, DrawerLayout drawerLayout, float displayWidthPercentage) {
        if (activity == null || drawerLayout == null) return;
        try {
            // 找到 ViewDragHelper 并设置 Accessible 为true
            Field leftDraggerField = drawerLayout.getClass().getDeclaredField("mLeftDragger");//Right
            leftDraggerField.setAccessible(true);
            ViewDragHelper leftDragger = (ViewDragHelper) leftDraggerField.get(drawerLayout);

            // 找到 edgeSizeField 并设置 Accessible 为true
            Field edgeSizeField = leftDragger.getClass().getDeclaredField("mEdgeSize");
            edgeSizeField.setAccessible(true);
            int edgeSize = edgeSizeField.getInt(leftDragger);

            // 设置新的边缘大小
            Point displaySize = new Point();
            activity.getWindowManager().getDefaultDisplay().getSize(displaySize);
            edgeSizeField.setInt(leftDragger, Math.max(edgeSize, (int) (displaySize.x * displayWidthPercentage)));
        } catch (NoSuchFieldException e) {
        } catch (IllegalArgumentException e) {
        } catch (IllegalAccessException e) {
        }
    }
}
